package com.yinuo.controller;

import com.alibaba.fastjson.JSON;
import com.yinuo.common.JsonResult;
import com.yinuo.entity.LinuxShellCmd;
import com.yinuo.entity.PageJson;
import com.yinuo.entity.WindowsDosCmd;
import com.yinuo.repository.DocRepository;
import com.yinuo.repository.LinuxRepository;
import com.yinuo.repository.WindowsRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/7/16.
 */
@Controller
@RequestMapping("windows")
public class WindowsController {
    private static Logger logger = LoggerFactory.getLogger(WindowsController.class);

    @Autowired
    private WindowsRepository windowsRepository;
    @Autowired
    private DocRepository docRepository;

    @RequestMapping("windowsCmdAdd")
    @ResponseBody
    public String toAddCmd(WindowsDosCmd lsc){
        WindowsDosCmd dosCmd = windowsRepository.findByKey(lsc.getKey());
        boolean exists = dosCmd==null?false:true;
        if(exists){
            return JsonResult.toFaild("命令已存在");
        }
        try {
            windowsRepository.save(lsc);
            return JsonResult.toSuccess();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return JsonResult.toFaild(String.format("保存失败：%s",e.getMessage()));
        }
    }

    @RequestMapping("windowsCmdQuery")
    @ResponseBody
    public String toQueryCmd(@RequestParam(defaultValue = "0") int curPage, int pagesize, String keyword){
        String json = null;
        if(StringUtils.isEmpty(keyword)){
            Sort sort = new Sort(Sort.Direction.ASC,"key");
            Page<WindowsDosCmd> p = windowsRepository.findAll(PageRequest.of(curPage,pagesize,sort));
            PageJson<WindowsDosCmd> pj = new PageJson();
            pj.setTotal(p.getTotalElements());
            pj.setData(p.getContent());
            json = JSON.toJSONString(pj);
        }else{
            Sort sort = new Sort(Sort.Direction.ASC,"key");
            Page<WindowsDosCmd> p = null;
            try {
                p = windowsRepository.findAll(new Specification<WindowsDosCmd>() {
                    @Override
                    public Predicate toPredicate(Root<WindowsDosCmd> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                        List<Predicate> predicate = new ArrayList<>();
                        Predicate p1 = criteriaBuilder.like(root.get("key").as(String.class), "%" + keyword + "%");
                        Predicate p2 = criteriaBuilder.like(root.get("cmdDesc").as(String.class), "%" + keyword + "%");
                        predicate.add(criteriaBuilder.or(p1,p2));
                        Predicate[] pre = new Predicate[predicate.size()];
                        return criteriaQuery.where(predicate.toArray(pre)).getRestriction();
                    }
                }, PageRequest.of(curPage,pagesize,sort));
            } catch (Exception e) {
                e.printStackTrace();

            }
            PageJson<WindowsDosCmd> pj = new PageJson();
            pj.setTotal(p.getTotalElements());
            pj.setData(p.getContent());
            json = JSON.toJSONString(pj);
        }
        return json;
    }

    @RequestMapping("windowsCmdDel")
    @ResponseBody
    @Transactional
    public String windowsDel(String key){
        Integer b = windowsRepository.deleteWindowsDosCmdByKey(key);
        if(b>=1)
            return JsonResult.toSuccess();
        return JsonResult.toFaild();
    }

    @RequestMapping("windowsCmdUpdate")
    @ResponseBody
    public String windowsCmdUpdate(WindowsDosCmd lsc){
        try {
            windowsRepository.saveAndFlush(lsc);
            return JsonResult.toSuccess();
        } catch (Exception e) {
            return JsonResult.toFaild("更新失败！");
        }
    }

}
